package org.road0329.dlt698.axdr;

import org.road0329.dlt698.ReverseByteArrayInputStream;
import org.road0329.dlt698.ReverseByteArrayOutputStream;
import org.road0329.dlt698.asn1.axdr.AxdrType;

import java.nio.ByteBuffer;
import java.util.Arrays;
import java.util.Collections;

public class SETROADDAR extends AxdrType {
    private ByteBuffer dataCode = null;
    private SETOADDAR result = null;
    private AResultNormal data = null;

    public SETROADDAR() {
    }

    public void setDataCode(ByteBuffer dataCode) {
        this.dataCode = dataCode;
    }

    public void setAll(SETOADDAR result, AResultNormal data) {
        this.result = result;
        this.data = data;
    }

    public int decode(ReverseByteArrayInputStream input) throws Exception {
        int codeLength = 0;
        this.result = new SETOADDAR();
        codeLength += this.result.decode(input);
        this.data = new AResultNormal();
        codeLength += this.data.decode(input);
        return codeLength;
    }

    public int encode(ReverseByteArrayOutputStream output) throws Exception {
        int codeLength;
        if (this.dataCode != null) {
            codeLength = this.dataCode.remaining();
            while (this.dataCode.hasRemaining()) {
                output.write(this.dataCode.get());
            }
        } else {
            if (this.result != null && this.data != null) {
                codeLength = 0;
                codeLength += this.data.encode(output);
                codeLength += this.result.encode(output);
            } else {
                throw new RuntimeException("data or result is null");
            }
        }
        return codeLength;
    }

    public void encodeAndSave(int encodingSizeGuess) throws Exception {
        ReverseByteArrayOutputStream revOStream = new ReverseByteArrayOutputStream();
        revOStream.setBufSize(encodingSizeGuess);
        this.encode(revOStream);
        this.dataCode = ByteBuffer.wrap(revOStream.toByteArray());
        Collections.reverse(Arrays.asList(this.dataCode.array()));
    }

    @Override
    public String toString() {
        if (this.result != null && this.data != null) {
            return "sequence: {" + "result: " + this.result + ", data: " + this.data + "}";
        } else {
            return "result || data is null";
        }
    }
}



